package com.sky.filter;

import com.alibaba.fastjson.JSONObject;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Autowired
    JwtProperties jwtProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //获取路径，并判断
        String url = request.getRequestURL().toString();
        //登录请求直接放行
        if (url.contains("/login")){
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //获取令牌
        String token = request.getHeader("token");
        //令牌不存在
        if (!StringUtils.hasLength(token)){
            Result error = Result.error("NOT_LOGIN");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(error));
            return;
        }

        //解析令牌
        try {
            JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
        } catch (Exception e) {
            Result error = Result.error("NOT_LOGIN");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(error));
            return;
        }

        filterChain.doFilter(request,response);

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
